/**
 * QIBAO Service Inc All Rights Reserved @2018
 */
package com.qibao.toolkit.exception.strategy.impl;

import com.qibao.toolkit.exception.strategy.AbstractExceptionHandleStrategy;
import com.qibao.toolkit.exception.strategy.BaseExceptionHandleStrategyAware;
import com.qibao.toolkit.exception.strategy.ExceptionHandleType;
import com.qibao.toolkit.web.ResponseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 *
 * @author CuiBin
 * @version $Id: ConstraintViolationExceptionHandleStrategy.java, v0.1 2018/10/30 15:51 CuiBin Exp $$
 */
@ExceptionHandleType({ValidationException.class,ConstraintViolationException.class})
public class ConstraintViolationExceptionHandleStrategy extends AbstractExceptionHandleStrategy implements
        BaseExceptionHandleStrategyAware{
    private final  static Logger logger = LoggerFactory.getLogger(ConstraintViolationExceptionHandleStrategy.class);

    @Override
    public ResponseModel doHandle(Throwable throwable) {
        logger.warn("ValidationException:{}",throwable.getMessage(),throwable);
        if(throwable instanceof ConstraintViolationException){
            ConstraintViolationException violationException = (ConstraintViolationException) throwable;
            Set<ConstraintViolation<?>> constraintViolations = violationException.getConstraintViolations();
            String messages = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(","));
            return ResponseModel.ERROR(messages);
        }
        return ResponseModel.ERROR("ValidationException:"+throwable.getMessage());
    }
}
